package com.yxgc.chat.wildfire.nativelib;

import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.facebook.react.bridge.Callback;
import com.google.gson.Gson;
import com.yxgc.chat.wildfire.nativelib.bean.UiMessage;
import com.yxgc.chat.wildfire.nativelib.util.ErrStatus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.wildfirechat.message.ImageMessageContent;
import cn.wildfirechat.message.Message;
import cn.wildfirechat.message.MessageContent;
import cn.wildfirechat.message.SoundMessageContent;
import cn.wildfirechat.message.TextMessageContent;
import cn.wildfirechat.message.VideoMessageContent;
import cn.wildfirechat.model.Conversation;
import cn.wildfirechat.model.GroupInfo;
import cn.wildfirechat.model.UserInfo;
import cn.wildfirechat.remote.ChatManager;
import cn.wildfirechat.remote.GetMessageCallback;
import cn.wildfirechat.remote.GetRemoteMessageCallback;
import cn.wildfirechat.remote.SendMessageCallback;

class ConversionModel {
    Gson gson;
    public ConversionModel(){
        gson = new Gson();
    }
    public void  getUserInfo(String target, Callback callback){
        UserInfo userInfo = ChatManager.Instance().getUserInfo(target, false);
        callback.invoke(userInfo);
    }
    public void getConversionTitle(String target,String conversionType,Callback callback){
        if ("Group".equals(conversionType)){
            GroupInfo groupInfo = ChatManager.Instance().getGroupInfo(target, true);
            if (groupInfo != null) {
                String conversationTitle = groupInfo.name + "(" + groupInfo.memberCount + "人)";
                callback.invoke(conversationTitle);
            }else {
                callback.invoke(target);
            }
        }else if ("Single".equals(conversionType)){
            getUserInfo(target, new Callback() {
                @Override
                public void invoke(Object... args) {
                    if (args!=null&&args.length>0){
                        UserInfo userInfo = (UserInfo) args[0];
                        String title =ChatManager.Instance().getUserDisplayName(userInfo);
                        callback.invoke(title);
//                    groupInfo = groupViewModel.getGroupInfo(conversation.target, true);
                    }else {
                        callback.invoke(target);
                    }
                }
            });
        }

    }

    /**
     * 加载会话消息
     * */
    public void loadMessage(String conversion,Callback callback,Callback errBack){
        Conversation conversation = gson.fromJson(conversion,Conversation.class);
        ChatManager.Instance().getWorkHandler().post(() -> {
            ChatManager.Instance().getMessages(conversation, 0, true, 20, null, new GetMessageCallback() {
                @Override
                public void onSuccess(List<Message> messageList, boolean hasMore) {
                    if (messageList != null && !messageList.isEmpty()) {
                        List<UiMessage> uiMsgs = new ArrayList<>();
                        for (Message msg : messageList) {
                            uiMsgs.add(new UiMessage(msg));
                        }
                        Log.e("yxgc","uiMsgs : "+new Gson().toJson(uiMsgs));

                        callback.invoke(uiMsgs);
                    } else {
                        ChatManager.Instance().getRemoteMessages(conversation, null, 0, 20, new GetRemoteMessageCallback() {
                            @Override
                            public void onSuccess(List<Message> messages) {
                                if (messages != null && !messages.isEmpty()) {
                                    List<UiMessage> uiMsgs = new ArrayList<>();
                                    for (Message msg : messages) {
//                                        if (msg.messageId != 0) {
                                        uiMsgs.add(new UiMessage(msg));
//                                        }
                                    }
                                    callback.invoke(uiMsgs);
                                } else {
                                    callback.invoke(new ArrayList<>());
                                }
                            }

                            @Override
                            public void onFail(int errorCode) {
                                errBack.invoke(ErrStatus.errCallBack(errorCode,"远程获取会话信息失败"));
                            }
                        });
                    }
                }

                @Override
                public void onFail(int errorCode) {
                    errBack.invoke(ErrStatus.errCallBack(errorCode,"本地获取会话信息失败"));
                }
            });
        });
    }
    public void sendMessage(Conversation conversation, MessageContent content,Callback callback){

        Message msg = new Message();
        msg.conversation = conversation;
        msg.content = content;
        ChatManager.Instance().sendMessage(msg, new SendMessageCallback() {
            @Override
            public void onSuccess(long messageUid, long timestamp) {
                callback.invoke(true);
            }

            @Override
            public void onFail(int errorCode) {
                callback.invoke(false);
            }

            @Override
            public void onPrepare(long messageId, long savedTime) {

            }
        });
    }

    public void sendTxtMsg(String conversation,String content,Callback callback){
        TextMessageContent txtContent = new TextMessageContent(content.trim());

        sendMessage(gson.fromJson(conversation,Conversation.class),txtContent,callback);

    }
    public void sendVideoMsg(String conversation, String filePath ,Callback c) {
        VideoMessageContent videoMessageContent = new VideoMessageContent(filePath);
        sendMessage(gson.fromJson(conversation,Conversation.class), videoMessageContent,c);
    }

    public void sendAudioFile(String conversation, String audioFilePath, int duration,Callback callback) {
        Uri audioPath = Uri.parse(audioFilePath);
        if (audioPath != null) {
            File file = new File(audioPath.getPath());
            if (!file.exists() || file.length() == 0L) {
                Log.e("ConversationViewModel", "send audio file fail");
                return;
            }

            SoundMessageContent soundContent = new SoundMessageContent(file.getAbsolutePath());
            soundContent.setDuration(duration);
            sendMessage(gson.fromJson(conversation,Conversation.class), soundContent,callback);
        }
    }


    public void sendImgMsg(String conversation, String imageFileThumbPath, String imageFileSourcePath,Callback callback) {
        // Uri.fromFile()遇到中文檔名會轉 ASCII，這個 ASCII 的 path 將導致後面 ChatManager.sendMessage()
        // 在 new File()時找不到 File 而 return
        Uri imageFileThumbUri = Uri.parse(Uri.decode(imageFileThumbPath));
        Uri imageFileSourceUri = Uri.parse(Uri.decode(imageFileSourcePath));

        ImageMessageContent imgContent = new ImageMessageContent(imageFileSourceUri.getEncodedPath());
        String thumbParam = ChatManager.Instance().getImageThumbPara();
        if (!TextUtils.isEmpty(thumbParam)) {
            imgContent.setThumbPara(ChatManager.Instance().getImageThumbPara());
        }
        sendMessage(gson.fromJson(conversation,Conversation.class),imgContent,callback);
    }


}
